﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Browser;
using System.Reflection;
using System.IO;
using System.Windows.Resources;
using System.Windows.Markup;
using System.Collections.Generic;

namespace PPFinance.Common
{
    public class DownloadingData
    {
        public long NeedDataLength { get; set; }
        public long FinishDataLength { get; set; }
        public string Url { get; set; }
    }

    public class DownLoader
    {

        static public List<DownloadingData> DownloadingList = new List<DownloadingData>();

        WebClient webClient = new WebClient();
        Uri address = null;
        DownloadingData currentData = new DownloadingData();
        public DownLoader(string url, Func<string, DownloadProgressChangedEventArgs, object> OnProgressChanged, Func<string, OpenReadCompletedEventArgs, object> OnReadCompleted)
        {
            currentData.Url = url;
            currentData.NeedDataLength = 0;
            currentData.FinishDataLength = 0;
            var rndUrl = url;
            if (url.IndexOf("?") > -1)
            {
                rndUrl += "&guid=" + Guid.NewGuid().ToString();
            }
            else
            {
                rndUrl += "?guid=" + Guid.NewGuid().ToString();
            }
            address = new Uri(rndUrl);
            webClient.OpenReadCompleted += (object sender, OpenReadCompletedEventArgs e) =>
            {
                DownloadingList.Remove(currentData);
                OnReadCompleted(url, e);
            };
            webClient.DownloadProgressChanged += (object sender, DownloadProgressChangedEventArgs e) =>
            {
                currentData.FinishDataLength = e.BytesReceived;
                currentData.NeedDataLength = e.TotalBytesToReceive;
                OnProgressChanged(url, e);
            };
        }

        public void Read()
        {
            webClient.OpenReadAsync(address);
            DownloadingList.Add(currentData);
        }



    }
}
